<template>
    <view class="purchase-page">

        <p class="navigation">VIP会员</p>

        <view class="message">
            <image src="../../static/images/purchase/mipmap-xxxhdpi/3.png" class="informationIcon"></image>
            <image src="../../static/images/purchase/mipmap-xxxhdpi/10.png" class="headPortrait"></image>
            <p class="nickname" @click="login">{{mobile}}</p>
            <p class="expire">{{expirationTime}}</p>
        </view>

        <view class="provisioning">
            <image src="../../static/images/purchase/mipmap-xxxhdpi/6.png" class="provisioningIcon"></image>
            <p>开通会员</p>
            <image src="../../static/images/purchase/mipmap-xxxhdpi/8.png" class="provisioningIcon"></image>
        </view>

        <view class="purchase">
            <view class="card" :class="{ 'active-card': isSelected === '周卡' }" @click="handleCardClick('周卡')">
                <view class="timeLimit"><p>限时特惠</p></view>
                <p class="type">周卡会员</p>
                <view><span class="symbol">￥</span><span class="price">{{ getCardPrice('周卡') }}</span></view>
                <image src="../../static/images/purchase/mipmap-xxxhdpi/9.png" class="optFor" :style="{ opacity: isSelected === '周卡'? 1 : 0 }"></image>
            </view>
            <view class="card" :class="{ 'active-card': isSelected === '月卡' }" @click="handleCardClick('月卡')">
                <view class="timeLimit"><p>限时特惠</p></view>
                <p class="type">月卡会员</p>
                <view><span class="symbol">￥</span><span class="price">{{ getCardPrice('月卡') }}</span></view>
                <image src="../../static/images/purchase/mipmap-xxxhdpi/9.png" class="optFor" :style="{ opacity: isSelected === '月卡'? 1 : 0 }"></image>
            </view>
            <view class="card" :class="{ 'active-card': isSelected === '年卡' }" @click="handleCardClick('年卡')">
                <view class="timeLimit"><p>限时特惠</p></view>
                <p class="type">年卡会员</p>
                <view><span class="symbol">￥</span><span class="price">{{ getCardPrice('年卡') }}</span></view>
                <image src="../../static/images/purchase/mipmap-xxxhdpi/9.png" class="optFor" :style="{ opacity: isSelected === '年卡'? 1 : 0 }"></image>
            </view>
        </view>

        <view class="notice">
            <p>支付19.9元成为月卡会员，过期自动失效，可重新购买，自动续期。</p>
        </view>

        <view class="payment" @click="open">
            <p>同意协议并立即支付开通会员</p>
        </view>
		
		<view v-if="errorMessage" class="error-message">{{errorMessage}}</view>

        <checkbox-group @change="handleCheckboxChange">
            <checkbox class="agreement" activeBorderColor="#D79151" iconColor="#D79151">
                开通会员前请务必仔细阅读<a href="#" class="serve">《会员服务协议》</a>规则
            </checkbox>
        </checkbox-group>

        <view class="privilege">
            <view class="headline">
                <image src="../../static/images/purchase/mipmap-xxxhdpi/4.png"></image>
                <span>会员权益</span>
                <image src="../../static/images/purchase/mipmap-xxxhdpi/5.png"></image>
            </view>
            <view class="content">
                <p>会员权益</p>
            </view>
        </view>

    </view>
</template>

<script setup>
	import md5 from 'js-md5';
	import CryptoJS from 'crypto-js';
    import { info } from '../../api/login';
    import { goods } from '../../api/list';
    import { preCreate } from '../../api/user';
	import { onShow } from "@dcloudio/uni-app";
    import {ref, onMounted, nextTick, onActivated } from 'vue';
	
	const mobile = ref('未登录'); // 用户手机号
    const expirationTime = ref('未开通会员服务'); // 会员到期时间
    const goodsData = ref([]); // 用于存储商品列表数据
    const isSelected = ref('周卡'); // 初始化为周卡被选中状态
	const isAgreeTerms = ref('0'); // 是否同意使用条款
	const errorMessage = ref(''); // 展示错误提示信息
	const orderInformation = ref(null) // 用户选择的商品信息
	const selectedIndex = ref(-1); // 用户选择的选项索引（初始化为 -1，表示未选择）
	const option = ref('') // 支付方式参数

	// 初次挂在执行函数
    onMounted(() => {
        getInformation(); // 用户信息
        placeAnOrder(); // 商品列表
		});
	
	// 登录后的第一次会进行页面更新
	let isFirstLoad = ref(true); 
	onShow(() => {
		if(isFirstLoad && uni.getStorageSync('token')){
			getInformation();
			placeAnOrder().then(() => {
			    const cardInfo = goodsData.value.find(item => item.title === '周卡');
			    if (cardInfo) {
			            orderInformation.value = cardInfo;
						console.log('当前选中订单的信息：', orderInformation.value);
						
			   }
			});
			isFirstLoad = false;
		}else if(!isFirstLoad && !uni.getStorageSync('token')){ // 退出后的第一次会进行页面更新
			getInformation();
			placeAnOrder();
			isFirstLoad = true;
		}
	})

    // 获取商品列表
    const placeAnOrder = async () => {
        try {
            const res = await goods();
            // console.log('接口返回的完整数据：', res);
            goodsData.value = res.data;

            if (res.code) {
                // 添加其他成功提示的逻辑
                console.log('成功获取商品列表');
            } else {
                // 添加显示错误提示信息的逻辑
                console.error('获取商品列表失败：', res.msg);
            }
        } catch (error) {
            console.error('获取商品列表过程中出现错误：', error.message);
        }
    };

    // 获取用户信息
    const getInformation = async () => {
        try {
            const res = await info();
            mobile.value = res.data.mobile;
            if (res.data.expired_time) {
                const originalDateTime = res.data.expired_time;
                console.log(originalDateTime);
                const dateOnly = originalDateTime.split(' ')[0];
                const year = dateOnly.split('-')[0];
                const month = dateOnly.split('-')[1];
                const day = dateOnly.split('-')[2];
                expirationTime.value = `${year} 年 ${month} 月 ${day} 日 + '到期'`;
            }

            // console.log('接口返回的完整数据：', res);

            if (res.code) {
                // 添加其他成功提示的逻辑
                console.log('成功获取用户信息');
            } else {
                // 添加显示错误提示信息的逻辑
                console.error('获取用户信息失败：', res.msg);
				mobile.value = ('未登录'); // 用户手机号
				expirationTime.value = ('未开通会员服务'); // 会员到期时间
            }
        } catch (error) {
            console.error('获取用户信息过程中出现错误：', error.message);
			mobile.value = ('未登录'); // 用户手机号
			expirationTime.value = ('未开通会员服务'); // 会员到期时间
        }
    };
	
	// 开通会员服务
	const open = () => {
		if(uni.getStorageSync('token')){
			if(isAgreeTerms.value){
				errorMessage.value = ('请先勾选《会员服务协议》')
			}else{
				errorMessage.value = ('')
				showActionsheet(['微信支付', '支付宝支付'])
			}
		}else{
			// 转向登录页面
			uni.navigateTo({
	        url: '/pages/purchase/login/login',
	        animationType: 'pop-in',
	        animationDuration: 1000,
			})
		}
	}
	
	// 定义选择框状态改变的事件处理函数
	const handleCheckboxChange = (event) => {
	    if (isAgreeTerms.value === 0) {
	        isAgreeTerms.value = 1;
	    } else {
	        isAgreeTerms.value = 0;
	    }
	    console.log('使用条款的勾选状态改变');
	};

    // 根据卡片类型获取对应的价格
    const getCardPrice = (cardType) => {
        const cardInfo = goodsData.value.find(item => item.title === cardType);
        return cardInfo? cardInfo.price : '';
    };

    // 处理卡片点击事件
    const handleCardClick = (cardType) => {
		isSelected.value = cardType;
		orderInformation.value = getSelectedCardData(cardType);
		console.log('当前选中订单的信息：', orderInformation.value);
		updateOtherCardsStyle(cardType);
    };

    // 根据选中的卡片类型获取对应的商品数据
    const getSelectedCardData = (cardType) => {
        return goodsData.value.find(item => item.title === cardType);
    };

    // 更新其他卡片的样式
    const updateOtherCardsStyle = (selectedCardType) => {
        const cards = ['周卡', '月卡', '年卡'];
        cards.forEach(card => {
            if (card!== selectedCardType) {
                nextTick(() => {
                    const cardElement = document.querySelector(`.${card}Card`);
                    if (cardElement) {
                        cardElement.classList.remove('active-card');
                        if (card === '周卡') {
                            cardElement.style.backgroundColor = 'white';
                        }
                    }
                });
            }
        });
    };
	
	// 发起支付
	const showActionsheet = (itemList) => {
		uni.showActionSheet({
			itemList: itemList,
			success: (res) => {
				// 将用户选择的选项索引存储到响应式变量中
				selectedIndex.value = res.tapIndex;
				console.log('用户选择了：' + itemList[res.tapIndex]);
				// console.log(res);
				option.value = selectedIndex.value ? 'ali' : 'wechat';
				purchase();
			},
			fail: (err) => {
				console.log('支付取消');
				option.value = ''; // 重置option.value
			}
		});
	};
	
    // 下单
	const purchase = async () => {
	    try {
	        const res = await preCreate({
				goods_id: orderInformation.value.id,
				pay_way: option.value,
			});
			
			// console.log(res.data.sn)
			
	        if (res.code) {
	            if(option.value == 'wechat'){ // 微信支付
					uni.requestPayment({
					    "provider": "wxpay",
					    "orderInfo": {
					        "appid": "wx036219d236272317",	// 微信开放平台 - 应用 - AppId
					        "noncestr": generateRandomString(), // 随机字符串
					        "package": "Sign=WXPay",		// 固定值
					        "partnerid": "1519236721",		// 微信支付商户号
					        "prepayid": res.data.sn, 		// 统一下单订单号
					        "timestamp": Math.floor(Date.now()/1000), // 时间戳（单位：秒）
					        "sign": wechatSign,					// 签名，这里用的 MD5/RSA 签名
						},
						success(res) {
							if (res.errMsg == "requestPayment:ok") {
							    console.log('支付成功', res);
								uni.showToast({
								    title: '微信支付成功',
								    icon: 'success',
								})
							}
						},
						fail(e) {
							console.log('微信支付失败，原因如下：', e);
							uni.showToast({
							    title: '微信支付失败',
							    icon: 'none',
							});
						}
					})
				}else if(option.value == 'ali'){ // 支付宝支付
					// 生成支付宝订单对象字符串
					const aliOrderInformation = {
					    title: orderInformation.value.title,
					    out_trade_no: res.data.sn,
					    price: res.data.money
					};
					const alipayOrderInfo = generateAlipayOrderInfo(aliOrderInformation);
					console.log(alipayOrderInfo);
					uni.requestPayment({
					    "provider": "alipay",
					    "orderInfo": alipayOrderInfo,
					    success(res) {
					        console.log('支付宝支付成功', res);
					        uni.showToast({
					            title: '支付宝支付成功',
					            icon: 'success',
					        });
					    },
					    fail(e) {
					        console.log('支付宝支付失败', e);
					        uni.showToast({
					            title: '支付宝支付失败',
					            icon: 'none',
					        });
					    }
					});
				}
	        } else {
	            // 添加显示错误提示信息的逻辑
	            console.error('下单失败：', res.msg);
	        }
	    } catch (error) {
			// 捕获下单过程中的错误
	        console.error('下单过程中出现错误：', error.message);
	    }
	};
	
	// 未登录状态下点击进入登录页面
	const login = () => {
		if(mobile.value === '未登录')
		uni.navigateTo({
		url: '/pages/purchase/login/login',
		animationType: 'pop-in',
		animationDuration: 1000,
		})
	}
	
	// 生成随机字符串
	const generateRandomString = () => {
	  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	  const length = 16; // 自定义字符串长度
	  let result = '';
	  for (let i = 0; i < length; i++) {
	    const randomIndex = Math.floor(Math.random() * characters.length);
	    result += characters.charAt(randomIndex);
	  }
	  return result;
	};
	
	// 生成微信签名
	const params = {
	  appId: 'wx036219d236272317',
	  nonceStr: generateRandomString(),
	  timeStamp: Math.floor(Date.now()/1000),
	  package: 'Sign=WXPay',
	  signType: 'MD5'
	};
	let stringA = '';
	for (let key in params) {
	  if (params[key] && key !== 'sign') {
	    stringA += `${key}=${params[key]}&`;
	  }
	}
	// 加上支付密钥并进行MD5签名
	stringA = stringA.slice(0, -1);  // 去掉最后一个 "&"
	const stringSignTemp = stringA + '&key=59f7d7fe287c182f76e67cd698f9e0a4';
	const wechatSign = md5(stringSignTemp).toUpperCase();  // 生成的签名
	// console.log(wechatSign)
	
	
	// 生成支付宝订单对象字符串
	const generateAlipayOrderInfo = (orderData) => {
	    // 构建支付宝订单请求的基本参数
	    const params = {
	        app_id: '2021005113655402',  // 支付宝应用的 AppID，需要替换为自己的
	        method: 'alipay.trade.app.pay',  // 支付宝的交易创建接口
	        format: 'JSON',  // 请求和响应的数据格式为 JSON
	        charset: 'utf-8',  // 字符编码
	        sign_type: 'RSA2',  // 签名类型，使用 RSA2 保证安全
	        timestamp: new Date().toISOString().replace('T', ' ').split('.')[0],  // 当前时间戳
	        version: '1.0',  // 接口版本号
	        biz_content: JSON.stringify({
	            subject: orderData.title,  // 订单标题，从订单数据中获取
	            out_trade_no: orderData.out_trade_no,  // 生成一个随机的商户订单号
	            total_amount: orderData.price.toString(),  // 订单总金额，从订单数据中获取
	            product_code: 'FAST_INSTANT_TRADE_PAY'  // 产品代码
	        })
	    };
		
		// 生成签名的函数
		const signParams = (params, privateKey) => {
		    // 将参数的键值对按照键的字母顺序排序并拼接成字符串
		    let signStr = Object.keys(params).sort().map(key => `${key}=${params[key]}`).join('&');
		    
		    // 使用RSA私钥签名，使用SHA-256算法
		    const sign = rsaSign(signStr, privateKey);
		    return sign;
		};
		
		// 使用RSA私钥进行签名的函数
		const rsaSign = (data, privateKey) => {
		    const sign = crypto.createSign('RSA-SHA256');
		    sign.update(data);
		    sign.end();
		    
		    // 对数据使用私钥进行签名，返回Base64编码的签名结果
		    const signature = sign.sign(privateKey, 'base64');
		    return signature;
		};
		
		// 生成请求字符串
		const generateAlipayOrderStr = (params, privateKey) => {
		    // 生成签名
		    const aliSign = signParams(params, privateKey);
		    
		    // 将生成的签名添加到请求参数中
		    params.sign = aliSign;
		
		    // 将参数拼接为字符串，方便作为支付宝请求的一部分
		    let alipayOrderStr = '';
		    for (const [key, value] of Object.entries(params)) {
		        alipayOrderStr += `${key}=${encodeURIComponent(value)}&`;
		    }
		    // 去除末尾多余的 "&"
		    return alipayOrderStr.slice(0, -1);
		};
		
		const privateKey = `-----BEGIN PRIVATE KEY-----
		MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhWXZIJAsnEpwGYJ/k9VhtRP/zZJE3yGujqejKOnpj+LMXsU9DG+4YAaTaG4psjvkhDCLGF+LEBaxGN/DJQz8dnqfnPtGrdfAvtFEzgA8xVgRqDRblaKeVAe9J3/I1Cw76HMyFnLpyuj8VBgCb//qkfjTXH0Oxb0TfiwM6AQSw9LqY0IeGDKtek/G3T1+8+r9IdAYCqiHTRatfa5ZwEAIzI0pIdEzY/U1YSVgWn4TwGM1a5d4QwFuqarmb1st3sgxS+nnPCSIa7k80c152k/sjzikA/Tv8Gz5UxAUQDRbBQolAkSjRWpi5HhD50S+AlUe7aExG33yOn/NfWJ2zbdnKQIDAQAB
		-----END PRIVATE KEY-----`;
	};
		
		
		
		
		
		
	    // // 生成签名，调用 signParams 函数
	    // const aliSign = signParams(params, 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhWXZIJAsnEpwGYJ/k9VhtRP/zZJE3yGujqejKOnpj+LMXsU9DG+4YAaTaG4psjvkhDCLGF+LEBaxGN/DJQz8dnqfnPtGrdfAvtFEzgA8xVgRqDRblaKeVAe9J3/I1Cw76HMyFnLpyuj8VBgCb//qkfjTXH0Oxb0TfiwM6AQSw9LqY0IeGDKtek/G3T1+8+r9IdAYCqiHTRatfa5ZwEAIzI0pIdEzY/U1YSVgWn4TwGM1a5d4QwFuqarmb1st3sgxS+nnPCSIa7k80c152k/sjzikA/Tv8Gz5UxAUQDRbBQolAkSjRWpi5HhD50S+AlUe7aExG33yOn/NfWJ2zbdnKQIDAQAB');
	    // // 将生成的签名添加到请求参数中
	    // params.sign = aliSign;
	    // let alipayOrderStr = '';
	    // // 将参数拼接为字符串，方便作为支付宝请求的一部分
	    // for (const [key, value] of Object.entries(params)) {
	    //     alipayOrderStr += `${key}=${encodeURIComponent(value)}&`;
	    // }
	    // // 去除末尾多余的 "&"
	    // return alipayOrderStr.slice(0, -1);

	
	
	// // 生成签名
	// const signParams = (params, privateKey) => {
	//     // 将参数的键值对按照键的字母顺序排序并拼接成字符串
	//     let signStr = Object.keys(params).sort().map(key => `${key}=${params[key]}`).join('&');
	//     // 使用 crypto-js 库的 HmacSHA256 算法对拼接后的字符串进行签名
	//     const sign = CryptoJS.HmacSHA256(signStr, privateKey).toString(CryptoJS.enc.Base64);
	//     return sign;
	// };

	

    
	
</script>

<style lang="scss" scoped>
    // 背景
.purchase-page {
        width: 100%;
        height: 200px;
        background-image: url('@/static/images/purchase/mipmap-xxxhdpi/1.png');
        background-size: 100%;
        // background-size: cover;
        background-repeat: no-repeat;
        // background-position: center;
        // background-color: #aaddfa;
    }

.navigation {
        // background-color: #fff123;
        text-align: center;
        padding: 50px 0 20px 0;
    }

.message {
        width: 100%;
        height: 150px;
        background-image: url('@/static/images/purchase/mipmap-xxxhdpi/2.png');
        background-size: 90%;
        background-repeat: no-repeat;
        background-position: center;
        position: relative;
        // background-color: #fff543;
    }

    // 图标
.informationIcon {
        width: 25%;
        height: 60%;
        // background-color: #223333;
        position: absolute;
        top: -10px;
        right: 40px;
    }

    // 头像
.headPortrait {
        border-radius: 50%;
        width: 60px;
        height: 60px;
        position: absolute;
        left: 50px;
        top: 35px;
    }

    // 昵称
.nickname {
        position: absolute;
        font-weight: bold;
        font-size: 15px;
        left: 120px;
        top: 43px;
    }

    // 到期
.expire {
        position: absolute;
        font-size: 11px;
        left: 120px;
        top: 68px;
    }

    // 开通标题
.provisioning {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 20px;
    }

.provisioning p {
        font-weight: bold;
        margin: 0 10px 0 10px;
        font-size: 15px;
    }

.provisioningIcon {
        width: 70px;
        height: 10px;
    }

    // 开通会员
.purchase {
        // background-color: #55ffff;
        margin: 0 auto;
        width: 90%;
        display: flex;
        align-items: center;
        justify-content: space-evenly;
    }

.card {
        width: 110px;
        height: 110px;
        // background-color: #ffffff;
        background-color: white;
        border: 1px solid #efc59f;
        border-radius: 5px;
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        transition: background-color 0.3s ease, opacity 0.3s ease;
    }

.active-card {
        background-color: #fff4e9;
    }

.timeLimit {
        width: 45px;
        height: 20px;
        // background-color: #aa00ff;
        font-size: 5px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-image: url('@/static/images/purchase/mipmap-xxxhdpi/7.png');
        background-size: 100%;
        background-repeat: no-repeat;
        background-position: center;
        position: absolute;
        left: -5px;
        top: -10px;
    }

.timeLimit p {
        font-size: 9px;
    }

.type {
        font-size: 12px;
    }

.price {
        font-size: 22px;
        color: #E18D3F;
    }

.symbol {
        font-size: 12px;
        color: #E18D3F;
        font-weight: bold;
    }

.optFor {
        position: absolute;
        width: 15px;
        height: 15px;
        right: 0px;
        bottom: 0px;
        opacity: 0;
        transition: opacity 0.3s ease;
    }

    // 自动续费
.notice {
        // background-color: #ffaa7f;
        margin: 0 auto;
        width: 90%;
        font-size: 13px;
        margin-top: 10px;
        margin-bottom: 10px;
    }

    // 同意支付
.payment {
        margin: 0 auto;
        width: 90%;
        height: 50px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 17px;
        border-radius: 50px;
        background: linear-gradient(to right, #FFE0C4, #D79151);
        margin-top: 20px;
        background-color: #ff55ff;
    }

	// 提示信息
.error-message{
	display: flex;
	margin: 0 auto;
	width: 80%;
	font-size: 15px;
	padding: 5px 0 0 5px;
	color: #ff0000;
	// background-color: #55ffff;
	animation: shake 0.5s cubic-bezier(0.36, 0.07, 0.19, 0.97) both;
	animation-iteration-count: 1;
}

    // 会员服务协议
.agreement {
        display: flex;
        margin: 0 auto;
        width: 80%;
        font-size: 12px;
        margin-top: 20px;
        margin-bottom: 20px;
        // background-color: #aaff00;
    }

.agreement a {
        text-decoration: none;
    }

.serve {
        color: #D79151;
    }

    // 会员权益
.privilege {
        margin: 0 auto;
        width: 90%;
        height: 250px;
        background-color: #fffaf5;
    }

.headline {
        display: flex;
        align-items: center;
        justify-content: center;
        padding-top: 20px;
        padding-bottom: 20px;
        // background-color: #ff55ff;
    }

.headline image {
        width: 10px;
        height: 10px;
    }

.headline span {
        font-weight: bold;
        margin: 0 10px 0 10px;
        font-size: 15px;
    }

    // 内容
.content p {
        margin: 0 auto;
        width: 80%;
        margin-bottom: 20px;
        // background-color: #55aa7f;
        font-size: 13px;
    }
</style>